package com.ukao.pad.ui.stokin;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.mcxtzhang.commonadapter.rv.CommonAdapter;
import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.pad.R;
import com.ukao.pad.adapter.AddClothingAdapter;
import com.ukao.pad.adapter.AddClothingTwoAdapter;
import com.ukao.pad.adapter.RemoveClothingAdapter;
import com.ukao.pad.base.MvpFragment;
import com.ukao.pad.bean.AddClothingItem;
import com.ukao.pad.bean.StringBean;
import com.ukao.pad.consts.SaveParamets;
import com.ukao.pad.dialog.SelectNumDialogFragment;
import com.ukao.pad.eventbus.AppEvent;
import com.ukao.pad.eventbus.PayAmountEvent;
import com.ukao.pad.listener.MyOnItemClickListener;
import com.ukao.pad.presenter.AddClothingPesenter;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.DecimalUtil;
import com.ukao.pad.utils.KeyBoardUtil;
import com.ukao.pad.utils.L;
import com.ukao.pad.utils.T;
import com.ukao.pad.view.AddClothingView;
import com.ukao.pad.widget.ClearEditText;
import com.ukao.pad.widget.MyLRecyclerView;


import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * Created by ukaodev on 2017/5/24.
 * 添加衣物
 */

@SuppressLint("ValidFragment")
public class AddClothingProjectFragment extends MvpFragment<AddClothingPesenter> implements AddClothingView {
    @BindView(R.id.remove_recycler)
    RecyclerView removeRecycler;
    @BindView(R.id.key_search_btn)
    Button keySearchBtn;
    @BindView(R.id.add_edit)
    ClearEditText addEdit;
    @BindView(R.id.add_btn)
    Button addBtn;
    @BindView(R.id.add_layout)
    RelativeLayout addLayout;
    @BindView(R.id.all_recycler)
    RecyclerView mAllRecycler;
    @BindView(R.id.seach_recycler)
    MyLRecyclerView mSearchRecycler;
    @BindView(R.id.two_seach_recycler)
    MyLRecyclerView mTwoSearchRecycler;
    @BindView(R.id.no_data)
    TextView noData;
    @BindView(R.id.seach_layout)
    FrameLayout seachLayout;
    @BindView(R.id.key_add_btn)
    Button keyAddBtn;
    @BindView(R.id.search_edit)
    EditText searchEdit;
    @BindView(R.id.search_btn)
    Button searchBtn;
    @BindView(R.id.keyboard_layout)
    LinearLayout keyboardLayout;
    //是否为单选模式
    private boolean isSingle;
    Unbinder unbinder;

    //hederList
    private List<AddClothingItem> mRemoveData;
    AddClothingTwoAdapter mAllAdapter;
    /**
     * headerAdapter
     */
    CommonAdapter<AddClothingItem> mRemoveAdapter;
    public String selectNane = "";
    private int loadItem; /*加载类型*/
    private String productId = "";
    private int isCustomNum;
    private String unitText = "";
    private String pricingMode;
    private String totalServiceDesc;

    private boolean mHasLoadedOnce;
    private int mCurrentCounter = 0;
    private boolean hasMore = true;
    private boolean hasSearchMore = true;
    private static int pageSize = 30;  //一页的数量
    private static int searchPageSize = 100;  //search一页的数量
    private int pageNum = 0;  //页数
    private int searchingPageNum;  //搜索的页数
    private String selectId;
    private String proServiceId;
    private List<StringBean> mDesclist;
    public static final int TWO_LOADER = 2;
    public static final int ENIGHT_LOADER = 8;
    private ArrayList<AddClothingItem> mSearchlist;
    private AddClothingAdapter mStockinAdapter;
    private boolean unSelect;

    private StringBuffer mSearchBuffer;
    private AddClothingTwoAdapter mSearchAdapter;
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private LRecyclerViewAdapter mSearchLRecyclerViewAdapter;

    private String orderId;
    private boolean isEnabledKeyboard, isEnabledAdd, isEnabledSearch;

    public static Builder createBuilder() {
        return new Builder();
    }

    public static final class Builder {
        private boolean isEnabledSearch;
        private boolean isEnabledAdd;
        private boolean isSinge;
        private boolean isEnabledKeyboard;
        private int enterPos;
        private String pricingMode;
        private String orderId = "";
        private String selectid;
        private List<StringBean> mDesclist;
        private String productId = "";
        private String unitText;
        private int isCustomNum;


        public Builder() {
        }


        public Builder isEnabledSearch(boolean val) {
            isEnabledSearch = val;
            return this;
        }

        public Builder unitText(String var) {
            this.unitText = var;
            return this;
        }

        public Builder isCustomNum(int var) {
            this.isCustomNum = var;
            return this;
        }

        /**
         * 数据回显示默认选中
         */
        public Builder setDefaultMatchCheck(String selectid) {
            this.selectid = selectid;
            return this;
        }

        /**
         * 数据回显示多选的默认选中
         */
        public Builder setDefaultMoreMatchCheck(List<StringBean> mDesclist) {
            this.mDesclist = mDesclist;
            return this;
        }

        public Builder productId(String var) {
            this.productId = var;
            return this;
        }

        public Builder orderId(String val) {
            orderId = val;
            return this;
        }

        public Builder isEnabledAdd(boolean val) {
            isEnabledAdd = val;
            return this;
        }

        public Builder enterPos(int val) {
            enterPos = val;
            return this;
        }


        public Builder isSinge(boolean val) {
            isSinge = val;
            return this;
        }

        public Builder isEnabledKeyboard(boolean val) {
            isEnabledKeyboard = val;
            return this;
        }

        public Builder pricingMode(String val) {
            pricingMode = val;
            return this;
        }

        public AddClothingProjectFragment build() {
            return AddClothingProjectFragment.getInstance(isEnabledSearch, isEnabledAdd, isSinge, isEnabledKeyboard, enterPos, pricingMode, orderId);
        }
    }


    public static AddClothingProjectFragment getInstance(boolean isEnabledSearch, boolean isEnabledAdd, boolean isSinge, boolean isEnabledKeyboard,
                                                         int enterPos, String pricingMode, String orderId) {
        AddClothingProjectFragment fragment = new AddClothingProjectFragment();
        Bundle args = new Bundle();
        args.putBoolean("isEnabledSearch", isEnabledSearch);
        args.putBoolean("isEnabledAdd", isEnabledAdd);
        args.putBoolean("isSinge", isSinge);
        args.putBoolean("isEnabledKeyboard", isEnabledKeyboard);
        args.putInt("enterPos", enterPos);
        args.putString("pricingMode", pricingMode);
        args.putString("orderId", orderId);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            isEnabledSearch = getArguments().getBoolean("isEnabledSearch");
            isEnabledAdd = getArguments().getBoolean("isEnabledAdd");
            isSingle = getArguments().getBoolean("isSinge");
            isEnabledKeyboard = getArguments().getBoolean("isEnabledKeyboard");
            loadItem = getArguments().getInt("enterPos");
            pricingMode = getArguments().getString("pricingMode");
            orderId = getArguments().getString("orderId");
        }
    }

    @Override
    protected AddClothingPesenter createPresenter() {
        return new AddClothingPesenter(this);
    }


    public void setProductId(String productId, boolean mHasLoadedOnce) {
        this.productId = productId;
        if (loadItem != 0)
            this.mHasLoadedOnce = mHasLoadedOnce;
    }

    public void setProductIdUnit(String productId, int isCustomNum, String unitText, boolean mHasLoadedOnce, String proServiceId) {

        this.isCustomNum = isCustomNum; /*如果是1就弹对话框*/
        this.productId = productId;
        this.unitText = unitText; /*单位*/
        this.mHasLoadedOnce = mHasLoadedOnce;
        this.selectId = proServiceId;/*服务回显示id */

    }


    /**
     * 数据回显示默认选中
     */
    public void setDefaultMatchCheck(String selectid) {
        this.selectId = selectid;
    }

    /**
     * 数据回显示多选的默认选中
     */
    public void setDefaultMoreMatchCheck(List<StringBean> mDesclist) {
        this.mDesclist = mDesclist;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add_clothing_project, null);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    @Override
    protected void initView() {
        keyboardLayout.setVisibility(isEnabledKeyboard ? View.VISIBLE : View.GONE);
        addLayout.setVisibility(isEnabledAdd && !isEnabledKeyboard ? View.VISIBLE : View.GONE);
        keySearchBtn.setVisibility(!isEnabledSearch ? View.GONE : View.VISIBLE);
        keyAddBtn.setVisibility(!isEnabledAdd ? View.GONE : View.VISIBLE);
        seachLayout.setVisibility(isEnabledKeyboard ? View.VISIBLE : View.GONE);
        mAllRecycler.setVisibility(!isEnabledKeyboard ? View.VISIBLE : View.GONE);
        List<AddClothingItem> list = new ArrayList<>();
        initGridRecyclerView(mAllRecycler, 6);
        mAllAdapter = new AddClothingTwoAdapter(activity, list, R.layout.activity_add_clothing_list_item);
        mAllAdapter.setOnItemClickListener(mOnAllItemListener);
        mAllRecycler.setAdapter(mAllAdapter);
        //启用自定义键盘 才有上拉加载
        if (isEnabledKeyboard) {
            mSearchBuffer = new StringBuffer();
            mSearchlist = new ArrayList<>();
            int spanCount = 2;
            initGridRecyclerView(mSearchRecycler, spanCount);

            mSearchAdapter = new AddClothingTwoAdapter(activity, mSearchlist, R.layout.activity_add_clothing_list_item);
            mLRecyclerViewAdapter = new LRecyclerViewAdapter(mSearchAdapter);
            mSearchAdapter.setOnItemClickListener(mSearchItemClickListener);

            mSearchRecycler.setAdapter(mLRecyclerViewAdapter);
            //设置加载更多
            mSearchRecycler.setOnLoadMoreListener(mOnLoadMoreListener);
            //静止下拉刷新
            mSearchRecycler.setPullRefreshEnabled(false);

            mSearchLRecyclerViewAdapter = new LRecyclerViewAdapter(mSearchAdapter);
            initGridRecyclerView(mTwoSearchRecycler, spanCount);
            mTwoSearchRecycler.setAdapter(mSearchLRecyclerViewAdapter);
            //设置加载更多
            mTwoSearchRecycler.setOnLoadMoreListener(mOnTwoLoadMoreListener);
            //静止下拉刷新
            mTwoSearchRecycler.setPullRefreshEnabled(false);
        }
        if (!isSingle) {
            mRemoveData = new ArrayList<>();
            if (null != mDesclist && mDesclist.size() > 0) {
                //附加
                if (ENIGHT_LOADER != loadItem) {
                    for (StringBean bean : mDesclist) {
                        mRemoveData.add(new AddClothingItem(bean.getId(), bean.getName()));
                    }
                }
            }
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            removeRecycler.setLayoutManager(linearLayoutManager);
            mRemoveAdapter = new RemoveClothingAdapter(activity, mRemoveData);
            mRemoveAdapter.setOnItemClickListener(mRemoveflowItemListener);
            removeRecycler.setAdapter(mRemoveAdapter);
        }
    }

    /**
     * 加载更多
     */
    private OnLoadMoreListener mOnLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore() {
            if (hasMore) {
                requestData("");
            }
        }
    };
    /**
     * search加载更多
     */
    private OnLoadMoreListener mOnTwoLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore() {
            if (hasSearchMore) {
                requestData(searchEdit.getText().toString());
            }
        }
    };

    /**
     *
     */
    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        if (mHasLoadedOnce && mSearchAdapter != null) {
            if (mAllAdapter.getDatas().size() != 0 && mSearchAdapter.getDatas().size() != mAllAdapter.getDatas().size()) {
                mSearchAdapter.setDatas(mAllAdapter.getDatas());
                mSearchAdapter.notifyDataSetChanged();
            }
            searchEdit.setText("");
            noData.setVisibility(View.GONE);
            if (mSearchBuffer != null)
                mSearchBuffer.setLength(0);
        }


    }


    /**
     * 可见时
     */
    @Override
    public void onSupportVisible() {
        super.onSupportVisible();

        if (mHasLoadedOnce) return;
        requestData("");
    }

    private void requestData(String keyWords) {
        HashMap mHashMap = new HashMap<String, String>();
        switch (loadItem) {
            case AddClothingPesenter.PROJECT:  //项目
                mHashMap.put("pricingMode", pricingMode);
                mHashMap.put("accessToken", SaveParamets.getToken(_mActivity));
                mvpPresenter.projectData(mHashMap, loadItem);
                break;
            case AddClothingPesenter.SERVICE:   //服务
                //衣服服务111
                L.i("pricingMode=" + pricingMode);
                mHashMap.put("pricingMode", pricingMode);
                mHashMap.put("productId", productId);
                mHashMap.put("accessToken", SaveParamets.getToken(_mActivity));
                mHashMap.put("orderId", orderId);
                mvpPresenter.projectData(mHashMap, loadItem);
                break;
            case AddClothingPesenter.ANNEX:   //附件
                mHashMap.put("businessId", productId);
                mHashMap.put("accessToken", SaveParamets.getToken(_mActivity));
                mvpPresenter.projectData(mHashMap, loadItem);
                break;
            case AddClothingPesenter.COLOR: //颜色
                mHashMap.put("accessToken", SaveParamets.getToken(_mActivity));
                if (!TextUtils.isEmpty(keyWords)) {
                    searchingPageNum++;
                    mHashMap.put("keywords", keyWords);
                    mHashMap.put("pageNum", String.valueOf(searchingPageNum));
                    mHashMap.put("pageSize", String.valueOf(searchPageSize));
                    mvpPresenter.productColors(mHashMap, true);
                } else {
                    pageNum++;
                    mHashMap.put("pageNum", String.valueOf(pageNum));
                    mHashMap.put("pageSize", String.valueOf(pageSize));
                    mvpPresenter.productColors(mHashMap, false);
                }
                break;
            case AddClothingPesenter.FLAW:  //瑕疵
                mHashMap.put("accessToken", SaveParamets.getToken(_mActivity));
                if (!TextUtils.isEmpty(keyWords)) {
                    searchingPageNum++;
                    mHashMap.put("keywords", keyWords);
                    mHashMap.put("pageNum", String.valueOf(searchingPageNum));
                    mHashMap.put("pageSize", String.valueOf(searchPageSize));
                    mvpPresenter.productFlaws(mHashMap, true);
                } else {
                    pageNum++;
                    mHashMap.put("pageNum", String.valueOf(pageNum));
                    mHashMap.put("pageSize", String.valueOf(pageSize));
                    mvpPresenter.productFlaws(mHashMap, false);
                }
                break;
            case AddClothingPesenter.AFTER_WASHING_EFFECT:  //洗后效果
                mHashMap.put("accessToken", SaveParamets.getToken(_mActivity));
                if (!TextUtils.isEmpty(keyWords)) {
                    searchingPageNum++;
                    mHashMap.put("keywords", keyWords);
                    mHashMap.put("pageNum", String.valueOf(searchingPageNum));
                    mHashMap.put("pageSize", String.valueOf(searchPageSize));
                    mvpPresenter.productAfterWashingEffect(mHashMap, true);
                } else {
                    pageNum++;
                    mHashMap.put("pageNum", String.valueOf(pageNum));
                    mHashMap.put("pageSize", String.valueOf(pageSize));
                    mvpPresenter.productAfterWashingEffect(mHashMap, false);
                }
                break;
            case AddClothingPesenter.BRAND: //品牌
                mHashMap.put("accessToken", SaveParamets.getToken(_mActivity));
                if (!TextUtils.isEmpty(keyWords)) {
                    searchingPageNum++;
                    mHashMap.put("keywords", keyWords);
                    mHashMap.put("pageNum", String.valueOf(searchingPageNum));
                    mHashMap.put("pageSize", String.valueOf(searchPageSize));
                    mvpPresenter.productBrand(mHashMap, true);
                } else {
                    pageNum++;
                    mHashMap.put("pageNum", String.valueOf(pageNum));
                    mHashMap.put("pageSize", String.valueOf(pageSize));
                    mvpPresenter.productBrand(mHashMap, false);
                }
                break;
            case AddClothingPesenter.ATTACH: //附加
                mHashMap.put("businessId", productId);
                mHashMap.put("accessToken", SaveParamets.getToken(_mActivity));
                mvpPresenter.productAddService(mHashMap);
                break;
        }
    }


    private void clothingSelectEven(final int position, AddClothingItem item) {
        if (item == null) return;
        if (isCustomNum == 1) {
            SelectNumDialogFragment.createBuilder(getFragmentManager()).setmDialogTitle("服务:" + item.getName()).
                    setUnitPice("单价：" + item.getPrice() + "元/" + unitText).setUnitTitle(unitText).setListener((id, msg) ->
                    setDialogEvent(position, (String) msg)).show();
        } else if (loadItem == ENIGHT_LOADER) {
            SelectNumDialogFragment.createBuilder(getFragmentManager()).setmDialogTitle("附加服务:" + item.getName()).setUnitTitle("元")
                    .setListener((id, msg) ->
                            setDialogEvent(position, (String) msg)).show();
        } else {
            if (loadItem == TWO_LOADER) {
                item.setCount("1");
                String unitPrice = "单价：" + item.getPrice() + "元/" + unitText;
                item.setUnitpice(unitPrice);
                item.setUnitText(unitText);
            }
            notifyDataSetPage(position, item);
        }
    }

    private void setDialogEvent(int position, String count) {
        AddClothingItem item = mAllAdapter.getDatas().get(position);
        if (loadItem == TWO_LOADER) {/*服务*/
            String unitPrice = "";
            item.setCount(count);
            unitPrice = "单价：" + item.getPrice() + "元/" + unitText;
            item.setUnitpice(unitPrice);
            item.setUnitText(unitText);

        } else {
            item.setUnitText("元");
            item.setCount(count);


        }
        notifyDataSetPage(position, item);
    }


    private OnItemClickListener mSearchItemClickListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            if (CheckUtils.isEmpty(mSearchAdapter.getDatas())) return;
            AddClothingItem mAddClothingItem = mSearchAdapter.getItem(i);
            if (mAddClothingItem != null) {
                int indexOf = mSearchAdapter.getDatas().indexOf(mAddClothingItem);
                if (indexOf != -1)
                    clothingSelectEven(indexOf, mSearchAdapter.getDatas().get(indexOf));
            }
        }
    };


    private MyOnItemClickListener mOnAllItemListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object mObject, int position) {
            AddClothingItem mAddClothingItem = mAllAdapter.getItem(position);
            clothingSelectEven(position, mAddClothingItem);

        }
    };

    //1、修复remove all数据的反选
    //2、分页后选中的数据不从传过来的bean中比对
    private MyOnItemClickListener mRemoveflowItemListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            //moveAdapter效果改变
            AddClothingItem mItem = mRemoveAdapter.getItem(i);
            if (mItem == null) return;
            mRemoveAdapter.getDatas().remove(mItem);
            mRemoveAdapter.notifyDataSetChanged();
            if (mRemoveData.size() <= 0) removeRecycler.setVisibility(View.GONE);
            //选中数据中存在这个数据
            List<AddClothingItem> mAllData = mAllAdapter.getDatas();
            if (mAllData.contains(mItem)) {
                int index = mAllData.indexOf(mItem);
                if (index != -1) {
                    mAllData.get(index).setCheck(false);
                }
                mAllAdapter.notifyDataSetChanged();
            }
            if (null != mSearchAdapter && null != mSearchAdapter.getDatas()) {
                //mSearchAdapter 数据改变
                List<AddClothingItem> mSearchData = mSearchAdapter.getDatas();
                if (mSearchData.contains(mItem)) {
                    int index = mSearchData.indexOf(mItem);
                    if (index != -1) {
                        mSearchData.get(index).setCheck(false);
                    }
                    if (mSearchAdapter != null) mSearchAdapter.notifyDataSetChanged();
                }
            }
            //改变上边文字
            String str = "";
            JSONArray mJSONArray = new JSONArray();
            totalServiceDesc = "";
            for (AddClothingItem item : mRemoveData) {
                if (loadItem == ENIGHT_LOADER) {
                    str = str + item.getName() + item.getCount() + item.getUnitText() + "\n";
                } else {
                    str = str + item.getName() + "\n";
                }
                addDesc(mJSONArray, item);
            }
            if (str.endsWith("\n"))
                str = str.substring(0, str.length() - 1);
            AddClothingItem moreitem = new AddClothingItem();
            moreitem.setTotalServiceDescMoney(totalServiceDesc);
            moreitem.setName(str);
            moreitem.setSelectDesc(mJSONArray.length() == 0 ? "" : mJSONArray.toString());
            AppEvent.postHasData(AppEvent.Message.update, moreitem);
        }
    };


    /**
     * 通知界面刷新
     *
     * @param position 位置
     * @param item     点击当前数据
     */
    private void notifyDataSetPage(int position, AddClothingItem item) {
        if (isSingle) {    /*单选模式*/
            if (item.isCheck() && isCustomNum != 1) {
                return;
            }
              /*单选模式勾选*/
            item.setCheck(true);
            for (int i = 0; i < mAllAdapter.getDatas().size(); i++) {
                if (i != position) {
                    AddClothingItem listeItem = mAllAdapter.getDatas().get(i);
                    listeItem.setCheck(false);
                }
            }

        } else {   /*多选模式*/
            if (item.isCheck() && loadItem == ENIGHT_LOADER) {
            } else {
                List<AddClothingItem> mRemoveData = mRemoveAdapter.getDatas();
                item.setCheck(!item.isCheck());
                if (item.isCheck()) {
                    if (!mRemoveData.contains(item)) {
                        mRemoveData.add(item);
                    }
                    if (mRemoveData.size() > 0) removeRecycler.setVisibility(View.VISIBLE);

                } else {
                    if (mRemoveData.contains(item)) mRemoveData.remove(item);
                    if (mRemoveData.size() <= 0) removeRecycler.setVisibility(View.GONE);

                }

            }


        }

        sendData(item);
    }


    /**
     * 发送数据
     *
     * @param item
     */
    private void sendData(AddClothingItem item) {
        if (isSingle) {
            AppEvent.postHasData(AppEvent.Message.update, item);
            AppEvent.postNoData(AppEvent.Message.next);
        } else {
            String str = "";
            JSONArray mJSONArray = new JSONArray();
            totalServiceDesc = "";

            for (AddClothingItem s : mRemoveAdapter.getDatas()) {
                if (loadItem == ENIGHT_LOADER) {
                    str = str + s.getName() + s.getCount() + s.getUnitText() + "\n";
                } else {
                    str = str + s.getName() + "\n";
                }
                addDesc(mJSONArray, s);
            }
            if (str.endsWith("\n")) str = str.substring(0, str.length() - 1);
            AddClothingItem moreitem = new AddClothingItem();
            moreitem.setName(str);
            moreitem.setTotalServiceDescMoney(totalServiceDesc);
            moreitem.setSelectDesc(mJSONArray.length() == 0 ? "" : mJSONArray.toString());/*附件*/
            AppEvent.postHasData(AppEvent.Message.update, moreitem);
            moreitem = null;
        }
        if (!isSingle) {
            mRemoveAdapter.notifyDataSetChanged();
        }
        if (mSearchAdapter != null) mSearchAdapter.notifyDataSetChanged();
        mAllAdapter.notifyDataSetChanged();
    }


    /**
     * 添加附件
     *
     * @param mJSONArray
     * @param s
     */
    private void addDesc(JSONArray mJSONArray, AddClothingItem s) {
        try {

            JSONObject mJSONObject = new JSONObject();
            mJSONObject.put("id", s.getId());
            mJSONObject.put("name", s.getName());
            if (loadItem == ENIGHT_LOADER) {/*附加得添加金额*/
                String count = s.getCount();
                mJSONObject.put("amt", DecimalUtil.multiply(count));
                totalServiceDesc = DecimalUtil.add(totalServiceDesc, count);
            }
            mJSONArray.put(mJSONObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mHandler.removeCallbacksAndMessages(null);
        unbinder.unbind();
    }


    /**
     * 当更换项目时清除数据
     */
    public void clearSelect() {
        if (loadItem != 0) {
            selectId = null;
            mDesclist = null;
        }
//        if (CheckUtils.isEmpty(mAllAdapter.getDatas()) || loadItem == 0) return;
        if (loadItem == 0) {
            return;
        }
        if (loadItem == 2 || loadItem == 3 || loadItem == 8) { /*服务于 附件 和附加都要清楚数据*/
            mHasLoadedOnce = false;
            mAllAdapter.getDatas().clear();
            mAllAdapter.notifyDataSetChanged();
        } else {
            for (AddClothingItem addClothingItem : mAllAdapter.getDatas()) {
                addClothingItem.setCheck(false);
            }
            mAllAdapter.notifyDataSetChanged();

        }

        if (!CheckUtils.isNull(mRemoveAdapter) && !isSingle) {
            mRemoveData.clear();
            removeRecycler.setVisibility(View.GONE);
            mRemoveAdapter.notifyDataSetChanged();
        }
        if (mSearchAdapter != null) mSearchAdapter.notifyDataSetChanged();

    }


    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(PayAmountEvent event) {
        switch (event.getMessage()) {
            case unselect:
                clearSelect();
                break;
        }
    }

    Handler mHandler = new Handler();

    @Override
    public void getProjectSuccess(List<AddClothingItem> model) {
        mHasLoadedOnce = true;
        mAllAdapter.addDatas(model);
        //启用定义键盘的 才加载数据
        if (isEnabledKeyboard) {
            mCurrentCounter = model.size();
            mSearchAdapter.addDatas(model);
            mSearchRecycler.refreshComplete(pageSize);
            if (mCurrentCounter < pageSize) {
                hasMore = false;
                mSearchRecycler.setNoMore(true);
            }
        }
        if (!CheckUtils.isEmpty(selectId)) {
            for (int i = 0; i < mAllAdapter.getDatas().size(); i++) {
                AddClothingItem item = mAllAdapter.getDatas().get(i);
                if (selectId.equals(item.getId())) {
                    item.setCheck(true);
                }
            }
            mAllAdapter.notifyDataSetChanged();
        } else if (!CheckUtils.isEmpty(mDesclist)) {
            //单独判断附件模式
            if (loadItem == ENIGHT_LOADER) {
                for (int i = 0; i < mAllAdapter.getDatas().size(); i++) {
                    AddClothingItem mitem = mAllAdapter.getDatas().get(i);
                    String strId = mitem.getId();
                    for (int j = 0; j < mDesclist.size(); j++) {
                        if (strId.equals(mDesclist.get(j).getId())) {
                            if (loadItem == ENIGHT_LOADER) {
                                mitem.setCount(CheckUtils.isEmptyNumber(mDesclist.get(j).getAmt()));
                                mitem.setUnitText("元");
                            }
                            mitem.setPosition(i);
                            mitem.setCheck(true);
                            mRemoveData.add(mitem);
                        }
                    }
                }
                mAllAdapter.notifyDataSetChanged();
                if (!CheckUtils.isEmpty(mRemoveData))
                    mRemoveAdapter.notifyDataSetChanged();
                removeRecycler.setVisibility(View.VISIBLE);
            } else {
                for (int i = 0; i < mAllAdapter.getDatas().size(); i++) {
                    AddClothingItem mitem = mAllAdapter.getDatas().get(i);
                    String strId = mitem.getId();
                    //有多选删除的情况
                    if (null != mRemoveAdapter && mRemoveAdapter.getDatas().size() > 0) {
                        for (int j = 0; j < mRemoveAdapter.getDatas().size(); j++) {
                            if (strId.equals(mRemoveAdapter.getDatas().get(j).getId())) {
                                if (loadItem == ENIGHT_LOADER) {
                                    mitem.setCount(CheckUtils.isEmptyNumber(mDesclist.get(j).getAmt()));
                                    mitem.setUnitText("元");
                                }
                                mitem.setPosition(i);
                                mitem.setCheck(true);
                            }
                        }
                    } else {
                        //单选或者没有删除
                        for (int j = 0; j < mDesclist.size(); j++) {
                            if (strId.equals(mDesclist.get(j).getId())) {
                                if (loadItem == ENIGHT_LOADER) {
                                    mitem.setCount(CheckUtils.isEmptyNumber(mDesclist.get(j).getAmt()));
                                    mitem.setUnitText("元");
                                }
                                mitem.setPosition(i);
                                mitem.setCheck(true);
                            }
                        }
                    }
                }
                mAllAdapter.notifyDataSetChanged();
                removeRecycler.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void loadFail(String message) {
        T.show(message);
    }

    /**
     * 获得搜索数据成功
     *
     * @param model
     */
    @Override
    public void getSearchDataSuccess(List<AddClothingItem> model) {
//        Log.i("cj", "size " + (null != model ? model.size() + "" : "0"));
        mSearchRecycler.refreshComplete(searchPageSize);
        if (null == model || (mSearchAdapter != null && model.size() < searchPageSize)) {
            hasSearchMore = false;
            mTwoSearchRecycler.setNoMore(true); //静止上拉加载
        }
        if (1 == searchingPageNum && null != mSearchAdapter.getDatas()) {
            mSearchAdapter.getDatas().clear();
        }
        mSearchAdapter.addDatas(model);
        searchModeChanger(true);
        noData.setVisibility(mSearchAdapter.getDatas().size() == 0 ? View.VISIBLE : View.GONE);
        if (null != mRemoveAdapter && null != mRemoveAdapter.getDatas() && mRemoveAdapter.getDatas().size() > 0) {
            for (int i = 0; i < mSearchAdapter.getDatas().size(); i++) {
                AddClothingItem mitem = mSearchAdapter.getDatas().get(i);
                String strId = mitem.getId();
                for (int j = 0; j < mRemoveAdapter.getDatas().size(); j++) {
                    if (strId.equals(mRemoveAdapter.getDatas().get(j).getId())) {
                        if (loadItem == ENIGHT_LOADER) {
                            mitem.setCount(CheckUtils.isEmptyNumber(mDesclist.get(j).getAmt()));
                            mitem.setUnitText("元");
                        }
                        mitem.setPosition(i);
                        mitem.setCheck(true);
                    }
                }
            }
        }
        mSearchAdapter.notifyDataSetChanged();
    }

    private void searchModeChanger(boolean isSearchMode) {
        if (isSearchMode) {
            mSearchRecycler.setVisibility(View.GONE);
            mTwoSearchRecycler.setVisibility(View.VISIBLE);
        } else {
            mSearchRecycler.setVisibility(View.VISIBLE);
            mTwoSearchRecycler.setVisibility(View.GONE);
            searchingPageNum = 0;
            mTwoSearchRecycler.setNoMore(true);//恢复上拉加载
            hasSearchMore = true;
        }
    }

    @OnClick({R.id.add_btn, R.id.search_btn, R.id.key_search_btn, R.id.key_add_btn,
            R.id.Button1, R.id.Button2, R.id.Button3, R.id.Button4, R.id.Button5, R.id.Button6, R.id.Button7, R.id.Button8, R.id.Button9, R.id.Button10, R.id.Button11, R.id.Button12, R.id.Button13, R.id.Button14, R.id.Button15, R.id.Button16, R.id.Button17, R.id.Button18, R.id.Button19, R.id.Button20, R.id.Button21, R.id.Button22, R.id.Button23, R.id.Button24, R.id.Button25, R.id.Button26, R.id.Button27})
    public void onViewClicked(View view) {
        int i = view.getId();
        switch (i) {
            case R.id.key_add_btn:

                setVisibilityState(View.GONE, View.VISIBLE);
                KeyBoardUtil.showKeyboard(addEdit);
                break;
            case R.id.key_search_btn:

                setVisibilityState(View.VISIBLE, View.GONE);
                KeyBoardUtil.hideInputmethod(addEdit);
                break;
            case R.id.add_btn:
                String addtag = getText(addEdit);
                if (addtag.isEmpty()) return;
                hideSoftInput();
                AddClothingItem mDataBean = new AddClothingItem();
                mDataBean.setName(addtag);
                mDataBean.setId("");
                mAllAdapter.getDatas().add(0, mDataBean);
                clothingSelectEven(0, mDataBean);

                break;
            case R.id.search_btn:

                break;
            case R.id.Button27:
                if (mSearchBuffer.length() != 0) {
                    searchModeChanger(false);
                    if (mHasLoadedOnce && !CheckUtils.isEmpty(mAllAdapter.getDatas())) {
                        if (null != mRemoveAdapter && null != mRemoveAdapter.getDatas() && mRemoveAdapter.getDatas().size() > 0) {
                            for (AddClothingItem allItem : mAllAdapter.getDatas()) {
                                allItem.setCheck(false);
                                for (AddClothingItem removeoitem : mRemoveAdapter.getDatas()) {
                                    if (allItem.getId().equals(removeoitem.getId())) {
                                        allItem.setCheck(true);
                                    }
                                }
                            }
                        }
                    }
                    mSearchAdapter.setDatas(mAllAdapter.getDatas());
                    mSearchAdapter.notifyDataSetChanged();
                }
                noData.setVisibility(View.GONE);
                mSearchBuffer.setLength(0);
                searchEdit.setText("");
                break;
            default:
//                if (!mHasLoadedOnce) {
//                    T.show(getString(R.string.no_data_was_obtained));
//                    return;
//                }
//                if (CheckUtils.isEmpty(mAllAdapter.getDatas())) {
//                    T.show(getString(R.string.current_list_numerous));
//                    return;
//                }
                //搜索页数赋值为0
                searchingPageNum = 0;
                Button mButton = (Button) view;
                String s = mButton.getText().toString().trim();
                mSearchBuffer.append(s);
                searchEdit.setText(mSearchBuffer.toString());
                mHandler.removeCallbacksAndMessages(null);
                mHandler.postDelayed(() -> {
                    String searchContext = getText(searchEdit);
                    if (searchContext.isEmpty()) return;
                    try {
                        requestData(searchEdit.getText().toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }, 1000);
                break;
        }
    }


    private void setVisibilityState(int gone, int visible) {
        keyboardLayout.setVisibility(gone);
        addLayout.setVisibility(visible);
        mAllRecycler.setVisibility(visible);
        seachLayout.setVisibility(gone);
    }

}
